package lion.framework.core.task;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import lion.dev.lang.Init;
import lion.dev.lang.MapJ;
import lion.framework.core.conf.Config;
import lion.framework.core.conf.ConfigManager;
import lion.framework.core.task.builder.IScheduleBuilder;
import lion.framework.core.task.builder.ScheduleBuilderManager;
import lion.framework.core.task.cluster.ClusterInstance;
import lion.framework.core.task.cluster.DBClusterInstance;

/**
 * 自动任务初始化,该初始化器将在所有系统默认或用户创建的初始化器初始化完成后运行
 *
 * <pre>
 * time   2013 2013年7月16日 下午3:15:36
 * mail   hl_0074@sina.com
 * </pre>
 *
 * @author lion
 */
// @Initializer
public class AutoTaskInitializer implements Init {

	private static Log log = LogFactory.getLog(AutoTaskInitializer.class);

	@Override
	public void init() {

		if (log.isInfoEnabled()) {
			log.info("Auto Task Instance Id:" + AutoTaskManager.INSTANCEID);
		}

		// init taskcluster
		if (log.isDebugEnabled()) {
			log.debug("initial task clusters");
		}

		Config config = ConfigManager.getConfig("framework");
		List<MapJ> taskclusters = config.getList("framework.taskcluster");
		if (log.isDebugEnabled()) {
			log.debug("total taskclusters:" + taskclusters.size());
		}

		for (MapJ conf : taskclusters) {
			String id = conf.getString("id");
			String name = conf.getString("name");
			ClusterInstance ci = new DBClusterInstance(name, AutoTaskManager.INSTANCEID);

			if (log.isDebugEnabled()) {
				log.debug("clusterInstance:" + id + "  datasource:" + name);
			}
			AutoTaskManager.addClusterInstance(id, ci);
		}
		// init schedules
		if (log.isDebugEnabled()) {
			log.debug("init schedules");
		}
		List<MapJ> schedules = config.getList("framework.schedule");

		IScheduleBuilder builder = ScheduleBuilderManager.get(ScheduleBuilderManager.DEFAULT_BUILDER_NAME);

		for (MapJ sc : schedules) {

			ISchedule schedule = builder.build(sc);
			if (schedule != null && StringUtils.isNotBlank(schedule.getClusterId())) {
				ClusterInstance ci = AutoTaskManager.getClusterInstance(schedule.getClusterId());
				if (ci != null && !ci.isScheduleAssigned(schedule)) {
					ci.addSchedule(schedule);
				}
				continue;
			}
			AutoTaskManager.addSchedule(schedule);
		}
		// start timer
		AutoTaskManager.start();
		// start cluster guarders
		if (log.isDebugEnabled()) {
			log.debug("auto task initializer initialized");
		}
	}

	@Override
	public int order() {

		return Integer.MAX_VALUE;
	}
}
